package itdep.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

/**
 * @author Ivan Khalopik
 * @version $Revision: 4 $ $Date: 2010-06-10 13:13:16 +0000 (Thu, 10 Jun 2010) $
 */
public abstract class I18nUtils {

	public static Locale getLocaleFromString(final String value) {
		if (value != null) {
			final StringTokenizer tokens = new StringTokenizer(value, "_");
			final String language = tokens.hasMoreTokens() ? tokens.nextToken() : "";
			final String country = tokens.hasMoreTokens() ? tokens.nextToken() : "";
			String variant = "";
			String sep = "";
			while (tokens.hasMoreTokens()) {
				variant += sep + tokens.nextToken();
				sep = "_";
			}
			return new Locale(language, country, variant);
		}
		return null;
	}

	public static List<Locale> getCandidateLocales(final Locale locale) {
		final String language = locale.getLanguage();
		final String country = locale.getCountry();
		final String variant = locale.getVariant();

		final List<Locale> locales = new ArrayList<Locale>();
		if (variant.length() > 0) {
			locales.add(locale);
		}
		if (country.length() > 0) {
			locales.add((locales.size() == 0) ?
					locale : new Locale(language, country, ""));
		}
		if (language.length() > 0) {
			locales.add((locales.size() == 0) ?
					locale : new Locale(language, "", ""));
		}
		locales.add(Locale.ROOT);
		return locales;
	}
}
